package com.javaee.wordtree.controller;

import com.javaee.wordtree.common.Result;
import com.javaee.wordtree.entity.Word;
import com.javaee.wordtree.service.WordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/word")
@Slf4j
public class WordController {

    @Resource
    private WordService wordService;

    /**
     * 搜索单词接口
     * 
     * @param word   单词文本（必需）
     * @param userID 用户ID（可选）
     * @return 单词详细信息，包含翻译、短语、例句等
     */
    @GetMapping("/search")
    public Result<?> searchWord(@RequestParam("word") String word,
            @RequestParam(value = "userID", required = false) String userID) {

        log.info("收到单词搜索请求: word={}, userID={}", word, userID);

        // 参数校验
        if (word == null || word.trim().isEmpty()) {
            log.warn("单词参数为空");
            return Result.error("-1", "单词参数不能为空");
        }

        try {
            // 搜索单词
            Word searchResult = wordService.searchWord(word.trim(), userID);

            if (searchResult == null) {
                log.info("未找到单词: {}", word);
                return Result.error("404", "未找到该单词");
            }

            log.info("单词搜索成功: {}", word);
            return Result.success(searchResult);

        } catch (Exception e) {
            log.error("单词搜索失败: word={}, userID={}, error={}", word, userID, e.getMessage(), e);
            return Result.error("-1", "搜索失败：" + e.getMessage());
        }
    }

    /**
     * 检查单词是否存在
     * 
     * @param word 单词文本
     * @return 是否存在
     */
    @GetMapping("/exists")
    public Result<?> wordExists(@RequestParam("word") String word) {

        log.info("检查单词是否存在: {}", word);

        if (word == null || word.trim().isEmpty()) {
            return Result.error("-1", "单词参数不能为空");
        }

        try {
            boolean exists = wordService.wordExists(word.trim());
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查单词存在性失败: word={}, error={}", word, e.getMessage(), e);
            return Result.error("-1", "检查失败：" + e.getMessage());
        }
    }

    /**
     * 根据单词文本获取单词ID
     * 
     * @param word 单词文本
     * @return 单词ID
     */
    @GetMapping("/id")
    public Result<?> getWordId(@RequestParam("word") String word) {

        log.info("获取单词ID: {}", word);

        if (word == null || word.trim().isEmpty()) {
            return Result.error("-1", "单词参数不能为空");
        }

        try {
            Integer wordId = wordService.getWordIdByText(word.trim());
            if (wordId == null) {
                return Result.error("404", "未找到该单词");
            }
            return Result.success(wordId);
        } catch (Exception e) {
            log.error("获取单词ID失败: word={}, error={}", word, e.getMessage(), e);
            return Result.error("-1", "获取失败：" + e.getMessage());
        }
    }
}
